package com.rongshu.view.submitArticle.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.GlideUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.submitArticle.bean.DraftResponse;
import com.rongshu.view.submitArticle.bean.SavaDraftBody;
import com.rongshu.view.submitArticle.bean.SaveDraftResponse;
import com.rongshu.view.submitArticle.presenter.SubmitArticlePresenter;
import com.rongshu.view.submitArticle.view.SaveDraftView;
import com.rongshu.view.userInfo.entity.Article;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.rongshu.widget.xrichtext.EditTextPlus;
import com.utils.SPUtils;
import com.utils.StringUtils;
import com.utils.constants.SPKey;
import com.widget.PerformEdit;
import com.widget.dialog.BottomListDialog;
import com.widget.titlebar.OnKeyboardListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * created by zhengweis on 2018/11/8.
 * description：投稿
 */
public class SubmitArticleActivity extends BaseActivity<SubmitArticlePresenter> implements SaveDraftView {
    @BindView(R.id.head_content)
    RelativeLayout headContent;
    @BindView(R.id.article_title)
    EditText articleTitle;
    @BindView(R.id.before_step)
    RelativeLayout beforeStep;
    @BindView(R.id.next_step)
    RelativeLayout nextStep;
    @BindView(R.id.select_floder)
    RelativeLayout selectFloder;
    @BindView(R.id.save_file)
    TextView saveFile;
    @BindView(R.id.hide_keyboard)
    RelativeLayout hideKeyboard;
    @BindView(R.id.bottom_option)
    LinearLayout bottomOption;
    @BindView(R.id.content_length)
    TextView contentLength;
    @BindView(R.id.hint_layout)
    LinearLayout hintLayout;
    @BindView(R.id.upload_cover_image)
    ImageView uploadCoverImage;
    @BindView(R.id.article_content)
    EditTextPlus articleContent;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    public static final int FINISH_SUBMIT_ARTICLE = 107;//投稿成功，关闭相关页面
    public static final int SUBMIT_ARTICLE_SELECT_FLODER = 108;//选择草稿保存文集
    public static final int UPLOAD_COVER = 101;//上传封面requestCode
    public static final int UPLOAD_ILLUSTRATION = 102;//文章内容插图requestCode

    private PerformEdit performEdit;
    private int articleFloderId = 0;//文集id, 选择某个文件夹获取id，不选择默认为0
    private int draftId = 0;//草稿id
    private String initialTitle;//标题初始值，用于判断是否已经保存草稿
    private String initialContent;//内容初始值，用于判断是否已经保存草稿
    private String draftContent;//接口返回的草稿内容
    private String selectFloderName;//选择的文集名称
    private int articleLength = 0;//文章字数
    //头图的url
    private String topImgUrl;
    //头图操作选项
    private List<String> functions = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)  //软键盘自动弹出
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        if (bottomOption != null) {
                            bottomOption.setVisibility(isPopup ? View.VISIBLE : View.GONE);
                        }
                    }
                }).init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_submit_article;
    }

    @Override
    protected void initView() {
        performEdit = new PerformEdit(articleContent);
        Intent intent = getIntent();
        draftId = intent.getIntExtra(Constant.DRAFT_ID, 0);
        articleFloderId = intent.getIntExtra(Constant.FOLDER_ID, 0);
        //草稿内容（包括：头图、标题）
        SavaDraftBody body = (SavaDraftBody) intent.getSerializableExtra(Constant.DRAFT_DOBY);
        if (body != null) {
            //草稿头图
            if (!TextUtils.isEmpty(body.getTopImg())) {
                GlideUtils.loadImageView(this, uploadCoverImage, body.getTopImg(),
                        R.drawable.upload_article_top_img_select, R.drawable.upload_article_top_img_select);
                topImgUrl = body.getTopImg();
            }
            //草稿标题
            if (!TextUtils.isEmpty(body.getTitle())) {
                articleTitle.setText(body.getTitle());
                hintLayout.setVisibility(View.GONE);
            }
        }
        functions = new ArrayList<>();
        functions.add("更换");
        functions.add("删除");
    }


    @Override
    protected void initData() {
        setPresenter(new SubmitArticlePresenter(this), this);
        if (draftId != 0) {
            //草稿内容需要请求接口返回
            presenter.getDraft(draftId);
        }
        initDraft();
    }

    /**
     * 记录草稿标题,草稿内容 初始值,用于判断用户进行过编辑行为
     */
    private void initDraft() {
        initialTitle = articleTitle.getText().toString();
        initialContent = articleContent.getAllContent();
    }

    @OnTextChanged(value = R.id.article_title, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void titleTextChanged(Editable editable) {
        String s = editable.toString();
        hintLayout.setVisibility(s.length() == 0 ? View.VISIBLE : View.GONE);
    }

    @OnTextChanged(value = R.id.article_content, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void contentTextChanged(Editable editable) {
        Spanned spanned = Html.fromHtml(editable.toString());
        String result = spanned.toString().trim()
                .replace("\n", "");
        //Html.fromHtml在解析字符串时，会把每一张图片转换成一个占位符，所以此处计算文本长度应减去图片数量
        articleLength = result.length() - articleContent.getImage().size();
        contentLength.setText(TextUtils.isEmpty(result) ?
                "0 字" : articleLength + " 字");
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void finishAct(int flow) {
        if (flow == SubmitArticlePresenter.DELETE_DRIFT) {
            finish();
        } else if (flow == SubmitArticlePresenter.SAVE_DRIFT) {
            presenter.saveDraft(draftId, articleFloderId,
                    articleLength,
                    articleTitle.getText().toString(),
                    articleContent.getText().toString(),
                    topImgUrl);
        }
    }

    /**
     * 草稿保存成功
     */
    @Override
    public void saveDraftSuccess(SaveDraftResponse object) {
        if (object != null && object.getResponse() != null) {
            toast(TextUtils.isEmpty(selectFloderName) ? "已保存至第一个文集" : "已保存至" + selectFloderName);
            draftId = object.getResponse().getId();
            //草稿保存成功之后;用户依然有可能再次进行编辑,需要再次记录初始值
            initDraft();
        }
    }

    /**
     * 上传头图成功
     */
    @Override
    public void uploadTopImgSuccess(UpLoadImage upLoadImage) {
        topImgUrl = upLoadImage.getResponse().getImgUrl().get(0);
        Glide.with(this).load(topImgUrl).into(uploadCoverImage);
    }

    /**
     * 文章插图上传成功
     */
    @Override
    public void uploadInsertImgSuccess(UpLoadImage upLoadImage) {
        final List<String> imgUrl = upLoadImage.getResponse().getImgUrl();
        Glide.with(this).asBitmap().load(imgUrl.get(0)).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                articleContent.insertIndexImg(imgUrl.get(0), resource);
            }
        });
    }

    /**
     * 接口返回草稿内容
     */
    @Override
    public void callBackDraftContent(DraftResponse response) {
        if (response != null && response.getResponse() != null) {
            draftContent = response.getResponse().getArticleBody();
            List<String> imgSrcs = StringUtils.getImgList(draftContent);
            if (imgSrcs.size() > 0) {//内容存在图片，去把图片全部转成bitmap
                showLoading(true);
                presenter.urlsToBitmaps(imgSrcs);
            } else {//内容不存在图片，直接赋值就可以了
                String result = Html.fromHtml(draftContent).toString().trim();
                articleContent.setText(result);
                initialContent = articleContent.getText().toString();
            }
        }
    }

    /**
     * 返回草稿内容的bitmaps
     * Map<String, Bitmap> bitmaps  (key : 图片的url，value : 图片的bitmap)
     */
    @Override
    public void callBackDraftBitmaps(Map<String, Bitmap> bitmaps) {
        showLoading(false);
        presenter.dealWithContent(draftContent, bitmaps);
    }

    /**
     * 内容插入图片
     */
    @Override
    public void insertConentImg(String url, Bitmap bitmap) {
        articleContent.insertIndexImg(url, bitmap);
        //绑定完内容之后设置 initialContent
        initialContent = articleContent.getAllContent();
    }

    /**
     * 内容插入文本
     */
    @Override
    public void insertContentText(String content) {
        articleContent.append(content);
        //绑定完内容之后设置 initialContent
        initialContent = articleContent.getAllContent();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case FINISH_SUBMIT_ARTICLE:
                    Intent intent = new Intent();
                    intent.putExtra(Constant.INTENT_DATA, true);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case SUBMIT_ARTICLE_SELECT_FLODER:
                    if (data != null) {
                        Article.ResponseBean bean = (Article.ResponseBean) data.getSerializableExtra(Constant.INTENT_DATA);
                        articleFloderId = bean.getId();
                        selectFloderName = bean.getTitle();
                    }
                    break;
                case UPLOAD_COVER:
                    List<LocalMedia> aPictures = PictureSelector.obtainMultipleResult(data);
                    if (!TextUtils.isEmpty(aPictures.get(0).getCompressPath())) {
                        String topImgPath = aPictures.get(0).getCompressPath();
                        presenter.repairImg(topImgPath, UPLOAD_COVER);
                    }
                    break;
                case UPLOAD_ILLUSTRATION:
                    List<LocalMedia> bPictures = PictureSelector.obtainMultipleResult(data);
                    if (!TextUtils.isEmpty(bPictures.get(0).getCompressPath())) {
                        final String topImgPath = bPictures.get(0).getCompressPath();
                        presenter.repairImg(topImgPath, UPLOAD_ILLUSTRATION);
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.head_left, R.id.head_right, R.id.before_step, R.id.next_step, R.id.select_floder, R.id.save_file,
            R.id.hide_keyboard, R.id.upload_cover_image, R.id.add_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                onBackPressed();
                break;
            case R.id.head_right://进入投稿设置页面
                if (presenter.checkRule(articleTitle, articleContent)) {
                    String title = articleTitle.getText().toString();
                    //EditTextPlus(编译器)在插入图片的时候,为了格式区分,在每张图片前后加了"\n"换行;故在投稿之前需去除之前多加的"\n"
                    String content = articleContent.getText().toString()
                            .replace("\n" + EditTextPlus.article_start_label, EditTextPlus.article_start_label)
                            .replace(EditTextPlus.article_end_label + "\n", EditTextPlus.article_end_label);
                    presenter.toSettingAct(draftId, articleFloderId, title, content, topImgUrl);
                }
                break;
            case R.id.before_step:
                articleContent.setText("");
                break;
            case R.id.next_step:
                performEdit.undo();
                break;
            case R.id.select_floder://选择文集
                presenter.toArticleFloderAct();
                break;
            case R.id.save_file://保存草稿
                if (presenter.checkRule(articleTitle, articleContent)) {
                    String title = articleTitle.getText().toString();
                    //EditTextPlus(编译器)在插入图片的时候,为了格式区分,在每张图片前后加了"\n"换行;故在投稿之前需去除之前多加的"\n"
                    String content = articleContent.getText().toString()
                            .replace("\n" + EditTextPlus.article_start_label, EditTextPlus.article_start_label)
                            .replace(EditTextPlus.article_end_label + "\n", EditTextPlus.article_end_label);
                    presenter.saveDraft(draftId, articleFloderId, articleLength, title, content, topImgUrl);
                }
                break;
            case R.id.hide_keyboard:
                showKeyboard(false);
                break;
            case R.id.upload_cover_image:
                if (!TextUtils.isEmpty(topImgUrl)) {
                    BottomListDialog.Builder builder = new BottomListDialog.Builder(this);
                    builder.setCancle(getString(R.string.cancle));
                    builder.setFunctions(functions);
                    builder.setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, Dialog dialog) {
                            String function = functions.get(position);
                            if (TextUtils.equals(function, "删除")) {
                                uploadCoverImage.setImageDrawable(ContextCompat.getDrawable(SubmitArticleActivity.this,
                                        R.drawable.upload_article_top_img_select));
                                topImgUrl = "";
                            } else {
                                presenter.getPicture(UPLOAD_COVER, true);
                            }
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                } else {
                    presenter.getPicture(UPLOAD_COVER, true);
                }
                break;
            case R.id.add_image:
                presenter.getPicture(UPLOAD_ILLUSTRATION, false);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        String title = articleTitle.getText().toString();
        String content = articleContent.getAllContent();
        //标题||内容 变更，弹出是否保存的dialog
        if ((!TextUtils.equals(title, initialTitle) || !TextUtils.equals(content, initialContent))) {
            presenter.showHintDialog();
        } else {
            showKeyboard(false);
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.removePreferences(SPKey.FLODER_ID);
        PictureFileUtils.deleteCacheDirFile(this);
    }
}
